5.2 Express.js

  1. Motivations
    • We had to resolve pathnames when we developed a general web server with Node.js. Can we use pathnames in a different way instead of indicating resourse, i.e., files? For example, as some sorts of commands?
    • Is there a way to deal with several different types of HTTP method?
    • Is there an easier way to develope an application server with the HTTP protocol?

  2. Project

  3. Learning objectives
    • Understand the idea of Express.js, a very popular Node framework
    • Use of basic features in Express.js

  4. Prerequisites
    • Node.js

  5. Express.js
    • Fast, unopinionated, minimalist web framework for Node.js
      • Node web application framework
      • Creation of APIs
      • Routing framework

    • Typical structure
        1. Preparation
        2. Indication of use of middlewares
        3. Support of CORS
        4. Route handlers
      • Preparation
        const express = require('express');
        const app = express();
        const PORT = 3000;
        ...
        app.listen(PORT, function (err) {
            if (err) console.log(err);
            console.log("Server listening on PORT", PORT);
        });
        
      • Indication of use of middlewares
        (Note that a middleware in Express accesses request and response objects and takes some actions. Possibly modification of them. Refer Using Middlewares.)
        app.use(...);
        // E.g.,
        // app.use(express.urlencoded({ extended: false }));  // for the POST query data
        //   From Github: The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded.
        // app.use(express.json());
        
      • Support of CORS (Cross-Origin Resource Sharing)
        (Note. Different protocol and/or server name and/or port number)
        // Allow Cross-domain requests, i.e., CORS 
        //   Why do we need this?
        app.all('/*', function(req, res, next) {  // all(): any HTTP method; /*: any path
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "X-Requested-With");
            res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");  // Default: only GET and POST
            next();  // Express middleware function; To continue to next operations
        });
        
      • Route handlers
        (Note that a route is a combination of a HTTP method type and a path.)
        (Note that paths should start with '/'.)
        (Note that paths could be defined with a regular expression.)
        (Note that paths don't have to be used for resource files.)
        // get, post, put, delete, ..., all
        // E.g., app.post("/echo", function(req, res) { ... });
        // E.g., app.get("/calculator/adder", function(req, res) { ... });
        // req and res objects are different from those used in http.createServer().
        app.methodname(path, (req, res) => {
            ...
            res.send(...);
        })
        // path could be "*"
        get.all(path, (req, res) => {
            ...
            res.send(...);
        })
        

      • Trial 1: Let's build an Express app to send a message. You need to decide your port number.

        Connect to cs.tru.ca with your account, save the above code in hello_express.js, and complete and run it.
        You can test your express server from a web browser.
        (Note that if you did not install the 'express' module, then install it. $ npm install express)

    • Application-level|Router-level|Error-handling|]Built-in middlewares

    • How to get query data
      • For the HTTP GET method,
        app.get(path, (req, res) => {
            ...
            req.query.queryname
            ...
        });
        
      • For other HTTP methods, such as POST,
        app.use(express.urlencoded({ extended: false }));
        app.methodname(path, (req, res) => {
            ...
            req.body.queryname
            ...
        });
        

    • How to send a message back
      • res.send(message);

    • How to use other JavaScript files? E.g., server-side programs in the previous general web server with Node.js.
      (Note that an express app is generally used for an application.)

    • req - the request object
      • method
      • path
      • query
      • body
      • cookies
      • ...
    • res - the response object
      • set('Content-Type', 'text/html'), ...
      • send() - It automatically sets content-type.
      • json() - To send a JSON response; It also converts non-objects to JSON.
      • end() - To send data; To end without sending any data;
      • status()
      • ...

    • Trial 2: Let's build an Express app to echo a message sent from a client-side app. You need to decide your port number and path. The message comes with the HTTP GET method with the query, 'message=...'.

      Connect to cs.tru.ca with your account, save the above code in echo_express.js, and complete and run it.
      You can test your echo server with http://cs.tru.ca/~mlee/comp4620/Winter2025/5.%20back_end_technologies/echo_calculator_express.html
      Anything wrong? The use of a different port number makes a web browser think that your server-side app is from a different origin.

    • Trial 3: Let's build an Express app to echo a message sent from a client-side app. You need to decide your port number and path. The message comes with the HTTP GET method with the query, 'message=...'.
      You need to include the CORS code.

      Connect to cs.tru.ca with your account, save the above code in echo_express.js, and complete and run it.
      You can test your echo server with http://cs.tru.ca/~mlee/comp4620/Winter2025/5.%20back_end_technologies/echo_calculator_express.html

    • Trial 4: Let's build an Express app to support four arithmetic operations. You need to decide your port number and path. The message comes with the HTTP POST method with the query, 'opr1=...', 'opr2=...', and 'operation=add'.

      Connect to cs.tru.ca with your account, save the above code in calculator_express.js, and complete and run it.
      You can test your calculator server with http://cs.tru.ca/~mlee/comp4620/Winter2025/5.%20back_end_technologies/echo_calculator_express.html
      Can you add more code to support other arithmetic operations?

    • We will study Express.js a bit more when we study Web Service later.

  6. Further questions
    • How to use HTTPS with Express.js?
    • How to build up a web server system?
    • How to run an express app in multiple processes?
    • Other applications with Express.js?